#include <thread>
#include <functional>
#include "erpc/erpc.h"
#include "spd_logger.hpp"
#include "simpost_component.hpp"
#include "module/module_name.hpp"
#include "module/module_identity.pb.h"
#include "google/protobuf/wrappers.pb.h"

class publishAPP: public simpost::Component
{
public:
    explicit publishAPP() : Component("publisher", "V0.1.0") {}
    virtual ~publishAPP() = default;
    bool init(void) override final;
    void exit(void) override final;
private:
    void publisherApp(void);
    void topicDataGet(google::protobuf::Any &args);
private:
    int m_private_data;
};

bool publishAPP::init(void)
{
    LOG_INFO("publishAPP init");
    m_private_data = 1;
    erpc::erpc_topic_create(MODULE_ID_ACCESS, 15, std::bind(&publishAPP::topicDataGet, this, std::placeholders::_1));
    std::thread app([this]{ publisherApp(); });
    app.detach();
    return true;
}

void publishAPP::exit(void)
{
    LOG_INFO("publishAPP exit");
}

void publishAPP::publisherApp(void)
{
    google::protobuf::Any args;
    google::protobuf::Int32Value value;
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        value.set_value(m_private_data);
        args.PackFrom(value);
        erpc::erpc_topic_publish(MODULE_ID_ACCESS, 15, args);
        m_private_data++;
    }
}

void publishAPP::topicDataGet(google::protobuf::Any &args)
{
    google::protobuf::Int32Value value;
    value.set_value(m_private_data);
    args.PackFrom(value);
}

COMPONENT_REGISTER(publishAPP);